<template>
  <el-row class="main-container">
    <el-col :span="24" class="query-form-wrapper">
      <el-card shadow="hover">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true">
          <el-form-item label="所属系统" prop="systemId">
            <el-select
              v-model="queryParams.systemId"
              placeholder="请选择所属系统"
              style="width: 200px"
              @change="systemChange"
            >
              <el-option
                v-for="item in systemList"
                :key="item.menuId"
                :label="item.menuName"
                :value="item.menuId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="菜单名称" prop="menuName">
            <el-input
              v-model="queryParams.menuName"
              placeholder="请输入菜单名称"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </el-col>
    <el-col :span="24" class="content-wrapper">
      <el-card shadow="hover">
        <template #header>
          <el-row :gutter="10">
            <el-col :span="1.5">
              <el-button type="primary" plain icon="Plus" @click="handleAdd('-1')">新增</el-button>
            </el-col>
          </el-row>
        </template>
        <el-table
          :data="tableData"
          empty-text="暂无数据"
          row-key="menuId"
          :default-expand-all="false"
          border
          style="width: 100%"
        >
          <el-table-column
            key="menuName"
            prop="menuName"
            label="菜单名称"
            align="center"
            width="160"
          />
          <el-table-column prop="icon" label="图标" align="center" width="100">
            <template #default="scope">
              <svg-icon :icon-class="scope.row.icon" />
            </template>
          </el-table-column>
          <el-table-column
            key="menuCode"
            prop="menuCode"
            label="菜单编码"
            align="center"
            width="120"
          />
          <el-table-column key="sort" prop="sort" label="排序" align="center" width="100" />
          <el-table-column
            key="menuPath"
            prop="menuPath"
            label="菜单路径"
            header-align="center"
            width="200"
          />
          <el-table-column
            key="component"
            prop="component"
            label="组件路径"
            header-align="center"
          />
          <el-table-column prop="hiddenFlag" label="隐藏" align="center" width="80">
            <template #default="scope">
              <el-tag type="warning" v-show="scope.row.hiddenFlag === '1'">是</el-tag>
              <el-tag type="success" v-show="scope.row.hiddenFlag === '0'">否</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            fixed="right"
            width="180"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template #default="scope">
              <el-tooltip content="修改" placement="top">
                <el-button
                  link
                  type="primary"
                  icon="Edit"
                  @click="handleUpdate(scope.row)"
                ></el-button>
              </el-tooltip>
              <el-tooltip v-if="scope.row.menuLevel === 1" content="添加" placement="top">
                <el-button
                  link
                  type="primary"
                  icon="CirclePlus"
                  @click="handleAdd(scope.row.menuId)"
                ></el-button>
              </el-tooltip>
              <el-tooltip content="权限维护" placement="top">
                <el-button
                  link
                  type="primary"
                  icon="SetUp"
                  @click="handleAddPermission(scope.row.menuId)"
                ></el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button
                  link
                  type="warning"
                  icon="Delete"
                  @click="handleDelete(scope.row)"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-col>
    <el-dialog
      ref="formDialogRef"
      v-model="dialog.visible"
      :title="dialog.title"
      width="750px"
      append-to-body
      @close="closeDialog"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="菜单名称" prop="menuName">
              <el-input v-model="form.menuName" placeholder="请输入菜单名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜单编码" prop="menuCode">
              <el-input v-model="form.menuCode" placeholder="请输入菜单编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜单路径" prop="menuPath">
              <el-input v-model="form.menuPath" placeholder="请输入菜单路径" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="组件路径" prop="component">
              <el-input
                v-model="form.component"
                :disabled="form.menuLevel === 1"
                placeholder="请输入组件路径"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="图标" prop="icon">
              <el-input
                v-model="form.icon"
                :disabled="form.menuLevel === 2"
                placeholder="请输入图标"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input-number v-model="form.sort" :min="0" placeholder="请输入排序" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示状态" prop="hiddenFlag">
              <el-radio-group v-model="form.hiddenFlag">
                <el-radio value="0">显示</el-radio>
                <el-radio value="1">隐藏</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单级菜单" prop="singleFlag">
              <el-radio-group v-model="form.singleFlag">
                <el-radio value="0">否</el-radio>
                <el-radio value="1">是</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel()">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 权限维护对话框 -->
    <PermissionDialog v-model:visible="permDialogVisible" :parent-id="currentParentId" />
  </el-row>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref, useTemplateRef } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
import { useAuthStore } from '@/stores/modules/auth'
import { MenuFindDTO, MenuTree, SysMenu } from '@/api/system/menuType'
import { menuApi } from '@/api'
import { MenuTypeEnum } from '@/enums/dictEnum'
import svgIcon from '@/components/svgIcon/index.vue'
import PermissionDialog from '@/components/system/menu/PermissionDialog.vue'
const authStore = useAuthStore()
const loginUser = computed(() => authStore.loginUser)

/** 系统列表 */
const systemList = ref<SysMenu[]>([])

// 查询参数
const queryParams = reactive<MenuFindDTO>({
  menuName: '',
  systemId: process.env.VITE_APP_SYSTEM_ID,
  systemType: 1
})

// 表格数据
const tableData = ref<MenuTree[]>([])

// 对话框
const dialog = reactive({
  visible: false,
  title: ''
})

// 表单实例
const formRef = useTemplateRef<FormInstance>('formRef')

// 表单数据
const form = reactive<SysMenu>({
  menuId: '',
  menuName: '',
  menuCode: '',
  menuType: 1,
  menuPath: '',
  component: '',
  parentId: '',
  icon: '',
  sort: 0,
  hiddenFlag: '0',
  singleFlag: '0',
  permissionCode: '',
  systemId: '',
  systemType: 1,
  menuLevel: 1
})

// 表单校验规则
const rules = reactive({
  menuName: [{ required: true, message: '菜单名称不能为空', trigger: 'blur' }],
  menuCode: [{ required: true, message: '菜单编码不能为空', trigger: 'blur' }],
  menuPath: [{ required: true, message: '菜单路径不能为空', trigger: 'blur' }],
  component: [{ required: true, message: '组件路径不能为空', trigger: 'blur' }],
  icon: [{ required: true, message: '图标不能为空', trigger: 'blur' }],
  sort: [{ required: true, message: '排序不能为空', trigger: 'blur' }]
})

// 权限维护对话框
const permDialogVisible = ref(false)
const currentParentId = ref('-1')

onMounted(() => {
  findSystemList()
  handleQuery()
})

/** 系统选择改变事件 */
const systemChange = (val: string) => {
  queryParams.systemId = val
  const system = systemList.value.find((item) => item.menuId === val)
  queryParams.systemType = system?.systemType || 1
  handleQuery()
}

/** 查询菜单列表 */
const handleQuery = () => {
  findMenuTable()
}

/**
 * 新增菜单点击事件
 * @param parentId 父菜单ID
 */
const handleAdd = (parentId: string) => {
  reset()
  if (parentId === '-1') {
    form.parentId = queryParams.systemId
    form.systemType = queryParams.systemType
    form.component = 'Layout'
    form.menuLevel = 1
  } else {
    form.parentId = parentId
    form.icon = 'online'
    form.menuLevel = 2
  }
  dialog.title = '新增菜单'
  dialog.visible = true
}

/** 修改菜单点击事件 */
const handleUpdate = (row: SysMenu) => {
  dialog.title = '修改菜单'
  dialog.visible = true
  form.menuId = row.menuId
  form.menuName = row.menuName
  form.menuCode = row.menuCode
  form.menuType = row.menuType
  form.menuLevel = row.menuLevel
  form.menuPath = row.menuPath
  form.component = row.component
  form.parentId = row.parentId
  form.icon = row.icon
  form.sort = row.sort
  form.hiddenFlag = row.hiddenFlag
  form.singleFlag = row.singleFlag
  form.permissionCode = row.permissionCode
}

/** 删除菜单点击事件 */
const handleDelete = (row: SysMenu) => {
  ElMessageBox.confirm('确认删除菜单【' + row.menuName + '】吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        await deleteMenu(row)
        handleQuery()
      } catch (error) {
        ElMessage.error(error || '删除菜单失败')
        console.log(error)
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除菜单'
      })
    })
}

/** 提交表单 */
const submitForm = async () => {
  formRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      try {
        await saveMenu(form)
        handleQuery()
        closeDialog()
      } catch (error) {
        ElMessage.error(error || '保存菜单失败')
        console.log(error)
      }
    }
  })
}

/** 关闭对话框 */
const closeDialog = () => {
  dialog.visible = false
}

/** 取消按钮 */
const cancel = () => {
  dialog.visible = false
  reset()
}

/** 重置表单 */
const reset = () => {
  form.menuId = ''
  form.menuName = ''
  form.menuCode = ''
  form.menuType = 1
  form.menuPath = ''
  form.component = ''
  form.parentId = ''
  form.icon = ''
  form.sort = 0
  form.hiddenFlag = '0'
  form.singleFlag = '0'
  form.permissionCode = ''
  form.systemId = queryParams.systemId
  form.systemType = 1
  form.menuLevel = 1
  //formRef.value?.resetFields()
}
const handleAddPermission = (parentId: string) => {
  currentParentId.value = parentId
  permDialogVisible.value = true
}

//***接口********************************************* */

/** 查询系统列表 */
const findSystemList = () => {
  const queryParam = {
    menuType: MenuTypeEnum.SYSTEM
  }
  menuApi
    .findMenuList(queryParam)
    .then((res: any) => {
      systemList.value = res || []
    })
    .catch((err) => {
      ElMessage.error(err || '查询系统列表失败')
    })
}

/** 查询菜单列表 */
const findMenuTable = () => {
  menuApi
    .findMenuTree(queryParams)
    .then((res: any) => {
      tableData.value = res || []
    })
    .catch((err) => {
      ElMessage.error(err || '查询菜单列表失败')
    })
}

/** 保存菜单 */
const saveMenu = async (params: SysMenu) => {
  await menuApi
    .saveMenu(params)
    .then((res: any) => {
      handleQuery()
      closeDialog()
      ElMessage.success('保存菜单成功')
    })
    .catch((err) => {
      ElMessage.error(err || '保存菜单失败')
    })
}

/** 删除菜单 */
const deleteMenu = async (row: SysMenu) => {
  await menuApi
    .deleteMenu(row.menuId)
    .then((res: any) => {
      handleQuery()
      ElMessage.success('删除菜单成功')
    })
    .catch((err) => {
      ElMessage.error(err || '删除菜单失败')
    })
}
</script>

<style scoped lang="less">
.main-container {
  height: 100%;
  :deep(.el-card__body) {
    padding: 10px 20px;
  }
  :deep(.el-form-item--default) {
    margin-bottom: 0;
  }
  .query-form-wrapper {
    height: 52px;
    margin-bottom: 8px;
  }
  .content-wrapper {
    height: calc(100% - 60px);
    :deep(.el-card) {
      height: 100%;
    }
    :deep(.el-card__body) {
      height: 100%;
    }
  }
}
</style>
